package org.whh.automatic.ui.dialog;

import org.whh.automatic.util.CoordinateCapture;

import javax.swing.*;
import java.awt.*;
import java.io.Serial;

/**
 * 坐标捕获对话框
 * <p>
 * 用于捕获用户在屏幕上的鼠标坐标点。
 * 主要功能：
 * 1. 显示操作说明，指导用户如何捕获坐标。
 * 2. 实时显示鼠标坐标。
 * 3. 支持自动捕获静止坐标、F2确认、ESC取消。
 * 4. 捕获成功后自动关闭并返回坐标。
 * <p>
 * 典型用法：
 * CaptureCoordsDialog dialog = new CaptureCoordsDialog(parent);
 * dialog.setVisible(true);
 * if (dialog.isCoordinateCaptured()) {
 * Point p = dialog.getCapturedPoint();
 * // 使用捕获到的坐标
 * }
 */
public class CaptureCoordsDialog extends JDialog {
    @Serial
    private static final long serialVersionUID = 1L;

    private JLabel statusLabel;
    private JTextField xCoordField;
    private JTextField yCoordField;
    private JButton startButton;
    private CoordinateCapture captureUtil;
    private boolean coordinateCaptured = false;
    private Point capturedPoint = null;

    public CaptureCoordsDialog(JDialog parent) {
        super(parent, "捕获坐标", true);
        JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
        mainPanel.setBackground(Color.WHITE);
        JPanel infoPanel = new JPanel();
        infoPanel.setLayout(new BoxLayout(infoPanel, BoxLayout.Y_AXIS));
        infoPanel.setBackground(Color.WHITE);
        JLabel titleLabel = new JLabel("坐标捕获工具");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 16));
        titleLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
        infoPanel.add(titleLabel);
        infoPanel.add(Box.createRigidArea(new Dimension(0, 10)));
        JLabel instructionsLabel = new JLabel("<html>1. 点击\"开始捕获\"按钮<br>2. 将鼠标移动到目标位置<br>3. 保持鼠标静止5秒自动捕获<br>4. 按F2键确认当前坐标<br>5. 按ESC键取消捕获</html>");
        instructionsLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        instructionsLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
        infoPanel.add(instructionsLabel);
        infoPanel.add(Box.createRigidArea(new Dimension(0, 15)));
        statusLabel = new JLabel("就绪，等待开始捕获...");
        statusLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        statusLabel.setForeground(new Color(80, 80, 80));
        statusLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
        infoPanel.add(statusLabel);
        infoPanel.add(Box.createRigidArea(new Dimension(0, 15)));
        JPanel coordPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 5));
        coordPanel.setBackground(Color.WHITE);
        coordPanel.setAlignmentX(Component.CENTER_ALIGNMENT);
        JLabel xLabel = new JLabel("X坐标:");
        xLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        coordPanel.add(xLabel);
        xCoordField = new JTextField(5);
        xCoordField.setEditable(false);
        xCoordField.setFont(new Font("微软雅黑", Font.BOLD, 14));
        coordPanel.add(xCoordField);
        JLabel yLabel = new JLabel("Y坐标:");
        yLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        coordPanel.add(yLabel);
        yCoordField = new JTextField(5);
        yCoordField.setEditable(false);
        yCoordField.setFont(new Font("微软雅黑", Font.BOLD, 14));
        coordPanel.add(yCoordField);
        infoPanel.add(coordPanel);
        infoPanel.add(Box.createRigidArea(new Dimension(0, 10)));
        mainPanel.add(infoPanel, BorderLayout.CENTER);
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 0));
        buttonPanel.setBackground(Color.WHITE);
        startButton = new JButton("开始捕获");
        startButton.addActionListener(e -> startCapture());
        buttonPanel.add(startButton);
        mainPanel.add(buttonPanel, BorderLayout.SOUTH);
        initCaptureUtil();
        setContentPane(mainPanel);
        setSize(350, 380);
        setLocationRelativeTo(parent);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            @Override
            public void windowClosing(java.awt.event.WindowEvent e) {
                if (captureUtil != null) {
                    captureUtil.stopCapture();
                }
            }
        });
    }

    /**
     * 初始化坐标捕获工具
     * <p>
     * 创建CoordinateCapture实例并设置回调函数：
     * - 坐标捕获回调：处理捕获结果
     * - 坐标更新回调：更新界面显示
     */
    private void initCaptureUtil() {
        captureUtil = new CoordinateCapture(this::onCoordinateCaptured);
        captureUtil.setCoordinateUpdateListener(point -> {
            if (point != null) {
                SwingUtilities.invokeLater(() -> {
                    xCoordField.setText(String.valueOf(point.x));
                    yCoordField.setText(String.valueOf(point.y));
                });
            }
        });
    }

    /**
     * 启动捕获流程
     * <p>
     * 重置状态并启动坐标捕获过程：
     * 1. 重置捕获结果
     * 2. 禁用开始按钮
     * 3. 更新状态提示
     * 4. 启动坐标捕获
     */
    private void startCapture() {
        coordinateCaptured = false;
        capturedPoint = null;
        startButton.setEnabled(false);
        statusLabel.setText("正在捕获，将鼠标移动到目标位置并保持不动...");
        statusLabel.setForeground(Color.BLUE);
        captureUtil.startCapture();
    }

    /**
     * 处理坐标捕获事件
     * <p>
     * 处理坐标捕获工具返回的结果：
     * - 成功捕获：更新UI并自动关闭对话框
     * - 取消捕获：重置状态并允许重新开始
     *
     * @param point 捕获到的坐标点，如果为null表示用户取消了捕获
     */
    private void onCoordinateCaptured(Point point) {
        if (point != null) {
            coordinateCaptured = true;
            capturedPoint = point;
            SwingUtilities.invokeLater(() -> {
                statusLabel.setText("捕获成功！坐标: (" + point.x + ", " + point.y + ")");
                statusLabel.setForeground(Color.GREEN.darker());
                startButton.setEnabled(true);
                startButton.setText("重新捕获");
                captureUtil.verifyCoordinate(point);
                Timer timer = new Timer(1000, evt -> {
                    if (captureUtil != null) {
                        captureUtil.stopCapture();
                    }
                    dispose();
                });
                timer.setRepeats(false);
                timer.start();
            });
        } else {
            coordinateCaptured = false;
            capturedPoint = null;
            SwingUtilities.invokeLater(() -> {
                statusLabel.setText("捕获已取消，可以重新开始...");
                statusLabel.setForeground(Color.RED);
                startButton.setEnabled(true);
            });
        }
    }

    /**
     * 获取是否成功捕获坐标
     *
     * @return true表示成功捕获，false表示未捕获或取消
     */
    public boolean isCoordinateCaptured() {
        return coordinateCaptured;
    }

    /**
     * 获取捕获到的坐标点
     *
     * @return 坐标点对象，如果未捕获则返回null
     */
    public Point getCapturedPoint() {
        return capturedPoint;
    }
} 